﻿#include "IdaTableView.h"
#include <QStandardItemModel>
#include <QMouseEvent>

namespace BaseWidget
{
    IdaTableView::IdaTableView(QWidget* parent)
        : QTableView(parent)
        , m_hoverRowIndex(-1)
    {
        viewport()->installEventFilter(this);
    }

    IdaTableView::~IdaTableView()
    {
    }

    void IdaTableView::mouseMoveEvent(QMouseEvent* event)
    {
        if (selectionBehavior() != QAbstractItemView::SelectRows) return;

        auto _model = qobject_cast<QStandardItemModel*>(model());
        if (_model == nullptr)
        {
            emit signal_hoverRowIndexChanged(-1, m_hoverRowIndex);
            m_hoverRowIndex = -1;
            return;
        }

        QBrush _backgroundItem_highlight(QColor(219, 239, 255));//#DBEFFF;
        QBrush _backgroundItem_normal(QColor(255, 255, 255));//#FFFFFF;

        QModelIndex _index = indexAt(event->pos());
        if (!_index.isValid())
        {
            // 没有行处于悬停状态
            QStandardItem* _item{};
            for (int _col = 0; _col < _model->columnCount(); ++_col)
            {
                _item = _model->item(m_hoverRowIndex, _col);
                if (_item)
                {
                    _item->setBackground(_backgroundItem_normal);
                }
            }

            emit signal_hoverRowIndexChanged(-1, m_hoverRowIndex);
            m_hoverRowIndex = -1;
            return;
        }

        auto _item = _model->itemFromIndex(_index);
        if (_item == nullptr)
        {
            emit signal_hoverRowIndexChanged(-1, m_hoverRowIndex);
            m_hoverRowIndex = -1;
            return;
        }

        int _hoverRowIndex = _item->row();

        if (_hoverRowIndex != m_hoverRowIndex)
        {
            QStandardItem* _item{};
            for (int _col = 0; _col < _model->columnCount(); ++_col)
            {
                _item = _model->item(m_hoverRowIndex, _col);
                if (_item)
                {
                    _item->setBackground(_backgroundItem_normal);
                }
                _item = _model->item(_hoverRowIndex, _col);
                if (_item)
                {
                    _item->setBackground(_backgroundItem_highlight);
                }
            }
        }
        update(); //及时更新，消除颜色延后更新的问题

        emit signal_hoverRowIndexChanged(_hoverRowIndex, m_hoverRowIndex);

        m_hoverRowIndex = _hoverRowIndex;
    }

}
